#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
motifs_graph_class_01 (motifs 09)
23 de septiembre de 2008
"""
#
import Image
import os
from numpy import array
import thread

class GraphMotif():
    def __init__(self, aminoacidos):
        self.aminos = aminoacidos
        self.normfrec = None
        self.msize = None
        self.imgbasename = None
        self.imgbase = None
        self.img = dict()
        self.base = r"AAS/base.bmp"
        
        self.read()
    
    def read(self):
        ""
        self.imgbasename = os.path.basename(self.base).split(".")[0]
        self.imgbase = Image.open(self.base, mode='r')
        imgdir = os.path.dirname(self.base)
        for aa in self.aminos:
            if aa in "syt":
                aaname = "p" + aa.upper()
            else:
                aaname = aa
            
            name = imgdir + os.sep + aaname + ".bmp"
            
            #por si no tengo la imagen de un determinado AA...
            try:
                self.img[aa] = Image.open(name, mode='r')
            except IOError:
                name = imgdir + os.sep + "X.bmp"
                self.img[aa] = Image.open(name, mode='r')
    
    def graph(self, frecuencias):
        ""
        self.msize = len(frecuencias[0])
        arfrec = array(frecuencias).astype(float)
        sum = arfrec.sum(0)
        normfrec = arfrec * 4 / sum
        self.normfrec = normfrec.swapaxes(0, 1) 
        
        self.make_img()
    
    def make_img(self):
        ""
        for idx in range(self.msize):
            pares = [(fr, item) for item, fr
                      in zip(self.aminos, self.normfrec[idx])]
            spares = sorted(pares,reverse=True)
            self.imgbase = self.imgbase.resize((50*self.msize,200))

            xpos = 50*idx
            ypos = 0
            for fr, item in spares:
                nwsz = int(50*fr)
                newimg = self.img[item].resize((50, nwsz))
                self.imgbase.paste(newimg, (xpos, ypos, xpos+50, ypos+nwsz))
                ypos += nwsz
        
    def show(self):
        thread.start_new_thread(self.show_threaded, (self.imgbase,))
               
    def show_threaded(self, img):
        img.show()
        
    def save(self, name):
        self.imgbase.save(name)
        
if __name__ == "__main__":
    
    frecs = [[1,10,6,2,5,3,4,8,0],
         [4,5,6,0,3,0,10,4,1],
         [1,10,2,2,2,8,1,0,0],
         [10,8,1,2,1,0,5,3,4],
         [3,2,10,5,1,10,4,3,2],
         [1,8,5,20,1,0,5,3,4],
         [5,4,1,5,10,7,8,9,3]
        ]
#
    size = 9
    AMINOS = "ARSYWLt"
    gmotif = GraphMotif(AMINOS)
    gmotif.graph(frecs)
    gmotif.show()
    exit=raw_input()